package com.asgard.crypto;

import org.apache.commons.lang3.RandomUtils;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 该类封装了AES128加密功能。
 */

public class AES128 {

    /**
     * 随机生成加密密钥。
     *
     * @return 随机生成的加密密钥
     */
    public static String getRandomKey() {
        return Hex.toHexString(RandomUtils.nextBytes(16));
    }

    /**
     * 对内容进行加密。
     *
     * @param content 需要加密的内容
     * @param key     密钥
     * @return 加密后的内容
     */
    public static String encrypt(String content, String key) {
        try {
            Cipher cipher = Cipher.getInstance("AES");
            byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretKey = new SecretKeySpec(Hex.decode(key), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] result = cipher.doFinal(contentBytes);
            return Hex.toHexString(result);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对内容进行解密。
     *
     * @param encryptedContent 需要解密内容
     * @param key              密钥
     * @return 解密后的内容
     */
    public static String decrypt(String encryptedContent, String key) {
        try {
            byte[] encoded = Hex.decode(encryptedContent);
            Cipher cipher = Cipher.getInstance("AES");
            SecretKeySpec secretKey = new SecretKeySpec(Hex.decode(key), "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] result = cipher.doFinal(encoded);
            return new String(result, StandardCharsets.UTF_8);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        }
    }

}